package com.lagouedu.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Author: chenhy
 * @Description:静态资源工具类
 * @Date: Create in 12:29 上午 2020/3/26
 */
public class StaticResourceUtil {

  /**
   * @return java.lang.String
   * @Author yuyz
   * @Description 获取文件的绝对路径
   * @Date 12:31 上午 2020/3/26
   * @Param [path]
   */
  public static String getAbsolutePath(String path) {
    String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
    absolutePath = absolutePath.replace("\\", "/") + path;
    absolutePath = absolutePath.replace("//", "/");
    return absolutePath;
  }

  /**
   * @return void
   * @Author yuyz
   * @Description 将静态文件读取并输出到对应的页面
   * @Date 12:35 上午 2020/3/26
   * @Param [ins, outs]
   */
  public static void outputStaticResource(InputStream ins, OutputStream outs) throws IOException {
    int count = 0;
    while (count == 0) {
      count = ins.available();
    }
    int resourceSize = count;

    //先输出响应头
    outs.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
    //对内容进行读取并输出
    int writtern = 0;
    int byteSize = 1024;
    byte[] bytes = new byte[1024];
    while (writtern < resourceSize) {
      //如果剩下的内容长度小于byteSize那么按实际长度读取
      if ((resourceSize - writtern) < byteSize) {
        byteSize = (resourceSize - writtern);
        bytes = new byte[byteSize];
      }
      ins.read(bytes);
      outs.write(bytes);

      //对内容进行输出
      outs.flush();
      writtern += byteSize;
    }

  }

}
